// pages/test_echart/test_echart.js

// import * as echarts from '../../ec-canvas/echarts'
import * as echarts from '../../ec-canvas/echarts.min.js'
import setOption from './setOpts'

let ecInstList = []

// 图表大概有以下这些类型
var charttype = ['pie', 'line', 'number', 'bar', 'table', 'ranking']

// 折线
function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    grid: {
      containLabel: true,
      left: 0,
      top: 20,
      right: 56,
      bottom: 0,
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: ['黄逸昊', '卢燕君', '陈晓虹', '梁慧敏', '刘嘉如'],
      // show: false
      axisTick: {
        show: false,      // 隐藏x轴刻度
      },
      axisLabel: {        // x轴 label
        fontSize: 10,
        interval: 0,
        hideOverlap: false,
      },
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        },
      },
      // show: false
      axisLabel: {        // y轴 label
        fontSize: 10,
      },
    },
    series: [{
      name: '记录数',
      type: 'line',
      smooth: true,
      data: [4, 3, 3, 2, 1,],
      label: {
        show: true,
        distance: 0,
        fontSize: 10,
      },
    },]
  };

  chart.setOption(option);
  return chart;
}

// 饼图
function initChart2(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    // backgroundColor: "#ffffff",
    tooltip: {
      show: true,
    },
    series: [{
      label: {
        normal: {
          fontSize: 12,
          formatter: '{b}: {c}',
        },
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['0%', '70%'],
      data: [{
        value: 55,
        name: '北京'
      }, {
        value: 20,
        name: '武汉'
      }, {
        value: 10,
        name: '杭州'
      }, {
        value: 20,
        name: '广州'
      }, {
        value: 38,
        name: '上海'
      }]
    }]
  };

  chart.setOption(option);
  return chart;
}

// 两条折线
function initChart3(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    grid: {
      containLabel: true,
      left: 0,
      top: 20,
      right: 56,
      bottom: 0,
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: ['黄逸昊', '卢燕君', '陈晓虹', '梁慧敏', '刘嘉如'],
      // show: false
      axisTick: {
        show: false,      // 隐藏x轴刻度
      },
      axisLabel: {        // x轴 label
        fontSize: 10,
      },
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        },
      },
      // show: false
      axisLabel: {        // y轴 label
        fontSize: 10,
      },
    },
    series: [{
      name: '记录数',
      type: 'line',
      smooth: true,
      data: [4, 3, 3, 2, 1,],
      label: {
        show: true,
        distance: 0,
        fontSize: 10,
      },
    },
    {
      name: '周期数',
      type: 'line',
      smooth: true,
      data: [5, 7, 1, 9, 6,],
      label: {
        show: true,
        distance: 0,
        fontSize: 10,
      },
    },]
  };

  chart.setOption(option);
  return chart;
}

// 柱状图
function initChart4(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    grid: {
      containLabel: true,
      left: 0,
      top: 20,
      right: 56,
      bottom: 0,
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
  //   dataZoom: [
  //     {
  //         id: 'dataZoomX',
  //         type: 'slider',
  //         xAxisIndex: [0],
  //         filterMode: 'filter', // 设定为 'filter' 从而 X 的窗口变化会影响 Y 的范围。
  //         start: 30,
  //         end: 70
  //     },
  // ],
    dataZoom: {
      type: 'slider',
      start: 0,
      end: 100,
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: ['黄逸昊', '卢燕君', '陈晓虹', '梁慧敏', '刘嘉如', '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', ],
      // show: false
      axisTick: {
        show: false,      // 隐藏x轴刻度
      },
      axisLabel: {        // x轴 label
        fontSize: 10,
        interval: 0,
        hideOverlap: false,
      },
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        },
      },
      // show: false
      axisLabel: {        // y轴 label
        fontSize: 10,
      },
    },
    series: [{
      name: '记录数',
      type: 'bar',
      smooth: true,
      data: [4, 3, 3, 2, 1, 12, 1, 5, 5, 5, 5, 5, 9, ],
      label: {
        show: true,
        // distance: 0,
        position: 'top',
        fontSize: 10,
      },
    },
    {
      name: '周期数',
      type: 'bar',
      smooth: true,
      data: [5, 7, 1, 9, 6, 12, 1, 7, 7, 4, 1, 6, 12, ],
      label: {
        show: true,
        // distance: 0,
        position: 'top',
        fontSize: 10,
      },
    },]
  };

  chart.setOption(option);
  return chart;
}

// 柱状图堆叠
function initChart5(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    grid: {
      containLabel: true,
      left: 0,
      top: 20,
      right: 56,
      bottom: 0,
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    // dataZoom: [
    //   {
    //     id: 'dataZoomX',
    //     type: 'slider',
    //     xAxisIndex: [0],
    //     filterMode: 'filter', // 设定为 'filter' 从而 X 的窗口变化会影响 Y 的范围。
    //     start: 30,
    //     end: 70
    //   },
    // ],
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: ['黄逸昊', '卢燕君', '陈晓虹', '梁慧敏', '刘嘉如' ],
      // show: false
      axisTick: {
        show: false,      // 隐藏x轴刻度
      },
      axisLabel: {        // x轴 label
        fontSize: 10,
        interval: 0,
        hideOverlap: false,
      },
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        },
      },
      // show: false
      axisLabel: {        // y轴 label
        fontSize: 10,
      },
    },
    series: [{
      name: '记录数',
      type: 'bar',
      stack: 'Ad',
      data: [4, 3, 3, 2, 1,],
      label: {
        show: true,
        // distance: 0,
        position: 'top',
        fontSize: 10,
      },
    },
    {
      name: '周期数',
      type: 'bar',
      stack: 'Ad',
      data: [5, 7, 1, 9, 6, ],
      label: {
        show: true,
        // distance: 0,
        position: 'top',
        fontSize: 10,
      },
    },]
  };

  chart.setOption(option);
  return chart;
}



Page({

  /**
   * 页面的初始数据
   */
  data: {
    chartList: [],
    echartsObjList: [],

    // ecsObj: {},

    ec: {
      onInit: initChart,
    },

    ec2: {
      onInit: initChart2,
    },

    ec3: {
      onInit: initChart3,
    },

    ec4: {
      onInit: initChart4,
    },

    ec5: {
      onInit: initChart5,
    },
  },

  addmore(e) {
    console.log('您点击了再添加一个');
  },

  // 获取报表设置列表
  getChartList() {
    let post = {
      limit: 0,
      oby: 'analysis_chart_id',
      page: 1,
    }
    wx.$post(3, 'All_analysis_chart/query_all_analysis_chart', post).then(res => {
      if(res.errcode !== 0) return
      // let rows = res.data.row.filter(item => item.component_type !== 'number'),
      let rows = res.data.row.filter(item => !['table', 'ranking', 'number'].includes(item.component_type)),
          blankObjList = []
      // rows.forEach((item, i) => item.checked = (i < 4))
      ecInstList = [ ...(new Array(rows.length)).values() ]
      rows.forEach((item, i) => item.checked = (i <= 15))
      rows.forEach((item, i) => {
        if(item.checked) this.getChartData(item)
        item.i = i
        blankObjList.push({
          chart: item,
          ec: {
            lazyLoad: true,
          },
        })
      })
      this.setData({
        chartList: rows,
        echartsObjList: blankObjList,
      })
    })
  },
  // 获取报表数据
  getChartData(chart) {
    let post = {
      analysis_chart_id: chart.analysis_chart_id,
      system_id: wx.getStorageSync('system_id'),
      time_group_id: 1,
    }
    wx.$post(3, 'All_analysis_chart/query_analysis_chart_data', post).then(res => {
      if(res.errcode !== 0) return
      console.log('获取报表数据', res.data.row[0], chart);
      let rows = res.data.row[0].Data,
          type = chart.component_type,
          xData = [],
          yData = []
      
      if(type === 'pie') {  // 饼图
        rows.forEach(item => yData.push({ value: item.tatolvalue || 0, name: item.linkname, }))
      } else if(['line', 'bar', ].includes(type)) {   // 折线图/柱状图
        let isStack = type === 'bar' && chart.classify_tier === '3',  // 堆叠柱状图
            baseObj = {}
        if(type === 'line') {
          baseObj = {
            smooth: true,
            label: {
              show: true,
              distance: 0,
              fontSize: 10,
            },
          }
        } else {
          baseObj = {
            label: {
              show: true,
              position: 'top',
              fontSize: 10,
            },
          }
          if(isStack) baseObj.stack = 'Ad'
        }
        let seriesNameArr = []
        rows.forEach((item, i) => {
          if(!i) {
            seriesNameArr = Object.keys(item).filter(key => !['linkname', 'tatolvalue', 'field_value'].includes(key) && item[key] !== item.field_value)
            seriesNameArr.forEach(name => {
              yData.push({
                name,
                type,
                data: [],
                ...baseObj,
              })
            })
          }
          xData.push(item.linkname)
          yData.forEach(ydata => {
            let { name, data, } = ydata
            data.push(item[name] || 0)
          })
        })
      }

      let ecInst = ecInstList[chart.i]
      if(!ecInst) this.initChart(chart, yData, xData)
      else console.log(465)
    })
  },
  initChart(item, yData, xData) {
    let ecComp = this.selectComponent('#mychart' + item.i)
    ecComp.init((canvas, width, height, dpr) => {
      let chart = echarts.init(canvas, null, {
        width,
        height,
        devicePixelRatio: dpr,    // new
      })
      canvas.setChart(chart)
      let option = setOption(item, yData, xData)
      chart.setOption(option)
      return chart;
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getChartList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})